package spring.cloud.tasks.tasks_assign_manager.schedule;

import lombok.Getter;
import lombok.Setter;
import org.apache.curator.framework.CuratorFramework;
import spring.cloud.tasks.tasks_assign_manager.task_item_assign.TaskItemAssignUtils;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Setter
@Getter
public class CronExpressionContextManager {
    private final String nameSpace;
    protected CuratorFramework curatorFramework;
    /**
     * 最新计算出来的CronExpression信息
     */
    public ConcurrentHashMap<String, CronExpressionContext> taskIdToCronExpressionContextMap = new ConcurrentHashMap<String, CronExpressionContext>();


    public CronExpressionContextManager(String nameSpace, CuratorFramework curatorFramework) {
        this.nameSpace = nameSpace;
        this.curatorFramework = curatorFramework;
    }

    public void refresh() throws Exception {
        //
        List<String> taskIdList = TaskItemAssignUtils.getTaskIdList(curatorFramework);
        List<String> enableTaskIdList = TaskItemAssignUtils.getEnableTaskIdList(curatorFramework, taskIdList);
        for (String taskId : taskIdToCronExpressionContextMap.keySet()) {
            CronExpressionContext cronExpressionContext = taskIdToCronExpressionContextMap.get(taskId);
            if (cronExpressionContext == null) {

            } else {
                if (!enableTaskIdList.contains(taskId)) {
                    cronExpressionContext.setEnable(CronExpressionContext.DISENABLE);
                }
            }
        }
        for (String taskId : enableTaskIdList) {
            TaskConfiguration taskConfiguration = new TaskConfiguration(taskId);
            String cronExpression = taskConfiguration.getCronExpression(curatorFramework);
            String pauseDatePeriod = taskConfiguration.getPauseDatePeriod(curatorFramework);
            String pauseTimePeriod = taskConfiguration.getPauseTimePeriod(curatorFramework);
            Integer preAssignMinutes = taskConfiguration.getPreAssignMinutes(curatorFramework);
            //
            CronExpressionContext cronExpressionContext = taskIdToCronExpressionContextMap.get(taskId);
            if (cronExpressionContext == null) {
                cronExpressionContext = new CronExpressionContext(taskId);
                cronExpressionContext.computeNextFireTime(cronExpression, pauseDatePeriod, pauseTimePeriod, preAssignMinutes);
                cronExpressionContext.setEnable(CronExpressionContext.ENABLE);
                taskIdToCronExpressionContextMap.put(taskId, cronExpressionContext);//替换
            } else {
                cronExpressionContext.computeNextFireTime(cronExpression, pauseDatePeriod, pauseTimePeriod, preAssignMinutes);
                cronExpressionContext.setEnable(CronExpressionContext.ENABLE);
            }


        }
    }

}
